
const db = wx.cloud.database()
const user = wx.getStorageSync('user')
module.exports = {
    addMessage({ post = {}, type, _receiverId, content = "" }) {
        // 添加新消息
        return db.collection("message").add({
            data: {
                type,
                _receiverId,
                user: {
                    nickName: user.nickName,
                    avatarUrl: user.avatarUrl
                },
                post: {
                    _id: post._id,
                    title: post.title
                },
                content,
                read: false,
                createTime: new Date().getTime()
            }
        })
    },
    readMessage(type, _receiverId) {
        // 设置已读消息
        return db.collection("message")
            .where({
                type,
                read: false,
                _receiverId,
            })
            .update({
                data: {
                    read: true
                }
            })
    },
    watchMessage(_openid, callback) {
        // 监听消息变化
        return db.collection("message").where({
            _receiverOpenid: _openid,
            read: false
        })
            .watch({
                onChange: callback,
                onError: () => {
                    console.log("连接断开")
                }
            })

    }
}